﻿using System;
using System.Data.Entity.Validation;
using System.Text;
using Castle.Core.Logging;
using Castle.DynamicProxy;

namespace BLL.Interceptor
{
    public class ExceptionInterceptor : IInterceptor
    {
        public ILogger Logger { get; set; }

        public void Intercept(IInvocation invocation)
        {
            try
            {
                invocation.Proceed();
            }
            catch (DbEntityValidationException ex)
            {
                StringBuilder errorMessage = new StringBuilder();
                foreach (var validationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errorMessage.AppendFormat("属性: {0} 错误: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
                LogError(invocation, errorMessage.ToString());
                throw new Exception(string.Format("实体模型验证错误：{0}", errorMessage));
            }
            catch (Exception ex)
            {
                LogError(invocation, ex.Message);
                throw;
            }
        }

        private void LogError(IInvocation invocation, string errorMessage)
        {
            var methodName = invocation.Method.Name;
            var args = invocation.Arguments;
            StringBuilder sb = new StringBuilder();
            int i = 0;
            foreach (var o in args)
            {
                sb.AppendFormat("参数：{0}：{1}", o, invocation.GetArgumentValue(i));
                i++;
            }
            Logger.ErrorFormat("这是一个全局记录器记录的错误,方法名：{0}，消息：{1}，详细信息：{2}", methodName, errorMessage, sb.ToString());
        }
    }
}